<template>
  <div class="user-setting-container">
    <h2 class="setting-title">用户设置</h2>
    
    <el-card class="setting-card">
      <template #header>
        <div class="card-header">
          <el-icon><VideoPlay /></el-icon>
          <span>启动动画设置</span>
        </div>
      </template>
      
      <div class="animation-setting">
        <!-- 动画启用开关 -->
        <div class="setting-row">
          <span class="setting-label">启用启动动画</span>
          <el-switch 
            v-model="animationEnabled"
            active-text="开"
            inactive-text="关"
            :loading="switchLoading"
            @change="handleToggleAnimation"
          />
        </div>
        
        <!-- 状态信息 -->
        <div v-if="statusMessage" class="status-message" :class="statusType">
          <el-icon v-if="statusType === 'success'"><CircleCheck /></el-icon>
          <el-icon v-if="statusType === 'error'"><CircleClose /></el-icon>
          {{ statusMessage }}
        </div>
        
        <!-- 动画选择器 -->
        <div class="animation-options">
          <h3 class="option-title">选择启动动画</h3>
          <el-radio-group v-model="selectedAnimation" class="animation-grid" @change="handleAnimationChange">
            <el-radio :label="1" border class="animation-card">
              <div class="animation-preview preview-1"></div>
              <div class="animation-name">科技流光</div>
              <div class="animation-desc">未来科技感的流光动画</div>
            </el-radio>
            <el-radio :label="2" border class="animation-card">
              <div class="animation-preview preview-2"></div>
              <div class="animation-name">星空漫游</div>
              <div class="animation-desc">浩瀚宇宙的星空动画</div>
            </el-radio>
            <el-radio :label="3" border class="animation-card">
              <div class="animation-preview preview-3"></div>
              <div class="animation-name">水墨江南</div>
              <div class="animation-desc">传统水墨风格动画</div>
            </el-radio>
          </el-radio-group>
        </div>
        
        <!-- 动画信息显示 -->
        <div v-if="userSettings" class="current-animation-info">
          <div class="setting-row">
            <span class="setting-label">当前动画</span>
            <div class="animation-display">
              <span>{{ getAnimationName(userSettings.animationId) }}</span>
              <el-tag type="success" v-if="userSettings.enable === 1">已启用</el-tag>
              <el-tag type="warning" v-else>已禁用</el-tag>
            </div>
          </div>
        </div>
        
        <!-- 预览按钮 -->
        <div class="preview-section">
          <el-button 
            type="primary" 
            @click="previewAnimation"
            class="preview-btn"
            :disabled="!selectedAnimation"
          >
            <el-icon><VideoCamera /></el-icon>
            预览动画
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { VideoPlay, VideoCamera, CircleCheck, CircleClose } from '@element-plus/icons-vue';
import { useUserStore } from '@/store/user'
import axios from 'axios';

const animationEnabled = ref(false);
const selectedAnimation = ref(null);
const switchLoading = ref(false);
const statusMessage = ref('');
const statusType = ref('');
const userStore = useUserStore();
const userSettings = ref(null); // 存储完整的用户设置数据

// 初始化加载用户设置
const loadUserSettings = async () => {
  try {
    // 检查用户是否有动画设置
    const haveRes = await axios.get('/app/animation/haveAnimation', {
      params: { userId: userStore.userInfo.id }
    });
    
    if (haveRes.data.code === 200) {
      // 获取动画列表设置
      const listRes = await axios.get('/app/animation/animationList', {
        params: { userId: userStore.userInfo.id }
      });
      
      if (listRes.data.code === 200 && listRes.data.data.List.length > 0) {
        userSettings.value = listRes.data.data.List[0];
        
        // 确保开关状态正确反映后端设置
        animationEnabled.value = userSettings.value.enable === 1;
        selectedAnimation.value = userSettings.value.animationId;
        
        if (animationEnabled.value) {
          statusMessage.value = `当前启用: ${getAnimationName(userSettings.value.animationId)}`;
          statusType.value = 'success';
        } else {
          statusMessage.value = '启动动画已关闭';
          statusType.value = 'info';
        }
      } else {
        userSettings.value = null;
        statusMessage.value = '用户没有动画设置';
        statusType.value = 'info';
      }
    } else {
      userSettings.value = null;
      animationEnabled.value = false;
      selectedAnimation.value = null;
      statusMessage.value = '用户没有动画设置';
      statusType.value = 'info';
    }
  } catch (error) {
    console.error('加载设置失败:', error);
    statusMessage.value = '加载动画设置失败';
    statusType.value = 'error';
  }
};

// 获取动画名称
const getAnimationName = (id) => {
  const animations = {
    1: '科技流光',
    2: '星空漫游',
    3: '水墨江南'
  };
  return animations[id] || `动画#${id}`;
};

// 处理动画开关切换
const handleToggleAnimation = async (isEnabled) => {
  switchLoading.value = true;
  try {
    // 使用当前选中的动画ID，如果没有则使用默认值
    const animationId = selectedAnimation.value || 1;
    
    const res = await axios.get('/app/animation/setAnimation', {
      params: {
        userId: userStore.userInfo.id,
        enable: isEnabled ? 1 : 0,
        animationId: animationId
      }
    });
    
    if (res.data.code === 200) {
      // 直接更新本地状态，不重新加载
      animationEnabled.value = isEnabled;
      
      // 更新userSettings
      if (userSettings.value) {
        userSettings.value.enable = isEnabled ? 1 : 0;
      } else {
        userSettings.value = {
          userId: userStore.userInfo.id,
          enable: isEnabled ? 1 : 0,
          animationId: animationId
        };
      }
      
      if (isEnabled) {
        // 如果开启但未选择动画，默认选择第一个
        if (!selectedAnimation.value) {
          selectedAnimation.value = 1;
          userSettings.value.animationId = 1;
        }
        statusMessage.value = `已启用: ${getAnimationName(selectedAnimation.value)}`;
      } else {
        statusMessage.value = '启动动画已关闭';
      }
      statusType.value = 'success';
    } else {
      // 回滚开关状态
      animationEnabled.value = !isEnabled;
      statusMessage.value = res.data.msg || '操作失败';
      statusType.value = 'error';
    }
  } catch (error) {
    console.error('设置失败:', error);
    // 回滚开关状态
    animationEnabled.value = !isEnabled;
    statusMessage.value = '操作失败: ' + (error.response?.data?.msg || error.message);
    statusType.value = 'error';
  } finally {
    switchLoading.value = false;
  }
};

// 处理动画选择变化
const handleAnimationChange = async (newAnimationId) => {
  try {
    // 无论开关状态如何，都保存动画选择
    const res = await axios.get('/app/animation/setAnimation', {
      params: {
        userId: userStore.userInfo.id,
        enable: animationEnabled.value ? 1 : 0,
        animationId: newAnimationId
      }
    });
    
    if (res.data.code === 200) {
      // 更新本地状态
      selectedAnimation.value = newAnimationId;
      
      if (userSettings.value) {
        userSettings.value.animationId = newAnimationId;
      } else {
        userSettings.value = {
          userId: userStore.userInfo.id,
          enable: animationEnabled.value ? 1 : 0,
          animationId: newAnimationId
        };
      }
      
      // 如果开关是开启状态，更新状态消息
      if (animationEnabled.value) {
        statusMessage.value = `已切换至: ${getAnimationName(newAnimationId)}`;
      }
      statusType.value = 'success';
    } else {
      // 回滚选择
      if (userSettings.value) {
        selectedAnimation.value = userSettings.value.animationId;
      }
      statusMessage.value = '动画切换失败';
      statusType.value = 'error';
    }
  } catch (error) {
    console.error('切换失败:', error);
    // 回滚选择
    if (userSettings.value) {
      selectedAnimation.value = userSettings.value.animationId;
    }
    statusMessage.value = '动画切换失败: ' + error.message;
    statusType.value = 'error';
  }
};

// 处理动画预览
const previewAnimation = () => {
  if (!selectedAnimation.value) {
    ElMessage.warning('请先选择动画');
    return;
  }
  
  // 这里实际应调用预览接口，此处模拟预览效果
  ElMessage.success(`正在预览: ${getAnimationName(selectedAnimation.value)}`);
};

onMounted(() => {
  loadUserSettings();
});
</script>

<style scoped>
/* 保持原有样式不变 */
.user-setting-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.setting-title {
  color: #333;
  margin-bottom: 25px;
  font-weight: 600;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.setting-card {
  margin-bottom: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #333;
}

.card-header .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.setting-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 10px;
  border-bottom: 1px solid #f5f5f5;
}

.setting-label {
  font-size: 16px;
  color: #555;
}

.animation-options {
  margin-top: 25px;
}

.option-title {
  color: #444;
  margin-bottom: 20px;
  font-weight: 500;
  font-size: 17px;
}

.animation-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  width: 100%;
}

.animation-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  border-radius: 8px !important;
  transition: all 0.3s;
  height: 100%;
  width: 100%;
}

.animation-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-5px);
}

.animation-preview {
  width: 100%;
  height: 150px;
  border-radius: 6px;
  margin-bottom: 15px;
  background-size: cover;
  background-position: center;
  position: relative;
  overflow: hidden;
}

.preview-1 {
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  position: relative;
}

.preview-1::before {
  content: "";
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(to right, transparent, rgba(255,255,255,0.4), transparent);
  animation: shine 2s infinite;
}

.preview-2 {
  background: linear-gradient(135deg, #000428, #004e92);
  position: relative;
  overflow: hidden;
}

.preview-2::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(white, rgba(255,255,255,.2) 2px, transparent 9px);
  background-size: 30px 30px;
  animation: stars 20s linear infinite;
}

.preview-3 {
  background: linear-gradient(to bottom, #f0f2f0, #e9e4f0);
  position: relative;
}

.preview-3::before {
  content: "";
  position: absolute;
  top: 20px;
  left: 30px;
  width: 80px;
  height: 40px;
  border-radius: 50%;
  background: rgba(200, 200, 200, 0.1);
  box-shadow: 60px 80px 0 rgba(150, 150, 150, 0.1),
              30px 100px 0 rgba(170, 170, 170, 0.1);
}

.animation-name {
  font-weight: 600;
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.animation-desc {
  font-size: 13px;
  color: #777;
  text-align: center;
}

.preview-section {
  margin-top: 30px;
  text-align: center;
}

.preview-btn {
  padding: 10px 25px;
  font-size: 16px;
}

.status-message {
  margin-top: 15px;
  padding: 10px 15px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.status-message.success {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #e1f3d8;
}

.status-message.error {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
}

.status-message.info {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #e9e9eb;
}

.current-animation-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.animation-display {
  display: flex;
  align-items: center;
  gap: 10px;
}

@keyframes shine {
  0% { left: -100%; }
  100% { left: 100%; }
}

@keyframes stars {
  0% { background-position: 0 0; }
  100% { background-position: 300px 300px; }
}
</style>